﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Domain.Values
{
	using System.Web.Mvc;
	using Falcon.Core.Domain.Services;
	using Falcon.Core.Extensions;
	using Falcon.Core.Validation;
	using Falcon.Core.Validators;

	public class ResourceCreate : ValueBase<ResourceCreate>
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="ResourceCreate"/> class.
		/// </summary>
		public ResourceCreate()
		{
			this.LanguageService = Application.Resolve<ILanguageService>();
		}

		/// <summary>
		/// Gets or sets the language repository.
		/// </summary>
		/// <value>The language repository.</value>
		public ILanguageService LanguageService
		{
			get; 
			private set;
		}

		/// <summary>
		/// Gets or sets the language id.
		/// </summary>
		/// <value>The language id.</value>
		public int LanguageId
		{
			get;
			set;
		}

		/// <summary>
		/// Gets or sets the item key.
		/// </summary>
		/// <value>The item key.</value>
		public string ItemKey
		{
			get;
			set;
		}

		/// <summary>
		/// Gets or sets the item value.
		/// </summary>
		/// <value>The item value.</value>
		public string ItemValue
		{
			get;
			set;
		}

		/// <summary>
		/// Gets the languages.
		/// </summary>
		/// <value>The languages.</value>
		public SelectList Languages
		{
			get
			{
				return new SelectList(this.LanguageService.GetAll(), "Id", "Title", this.LanguageId);
			}
		}

		/// <summary>
		/// Validation rules for this instance.
		/// </summary>
		/// <returns></returns>
		public override Validator<ResourceCreate> Rules()
		{
			var rules = base.Rules();

			rules.Add(x => x.ItemKey)
				.NotEmpty(Resources.Errors.Required.Fmt(Resources.Titles.Key));

			rules.Add(x => x.ItemKey)
				.Custom(new ResourceUniqueKeyValidator(), Resources.Errors.ResourceKeyTaken);

			rules.Add(x => x.ItemValue)
				.NotEmpty(Resources.Errors.Required.Fmt(Resources.Titles.Value));

			return rules;
		}

		/// <summary>
		/// Validates this instance.
		/// </summary>
		public override void Validate()
		{
			this.Rules().Validate(this);
		}
	}
}